﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharepointSolutionInstaller.Views;
using SharepointSolutionInstaller.Resources;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using SharepointSolutionInstaller.Utils.Configuration;

namespace SharepointSolutionInstaller.Utils.SolutionDeployment
{

    /// <summary>
    /// Command for creating a retraction job.
    /// </summary>
    public class CreateRetractionJobCommand : JobCommand
    {
        Guid solutionId;
        internal CreateRetractionJobCommand(InstallProcess parent, Guid solutionId)
            : base(parent)
        {
            this.solutionId = solutionId;
        }

        internal override string Description
        {
            get
            {
                return CommonUIStrings.createRetractionJobCommand;
            }
        }

        protected internal override bool Execute()
        {
            try
            {
                SPSolution installedSolution = SPFarm.Local.Solutions[solutionId];

                //
                // Remove existing job, if any. 
                //
                if (installedSolution.JobExists)
                {
                    RemoveExistingJob(installedSolution);
                }

                if (installedSolution.Deployed)
                {
                    log.Info(CommonUIStrings.logRetract);
                    if (installedSolution.ContainsWebApplicationResource)
                    {
                        Collection<SPWebApplication> applications = installedSolution.DeployedWebApplications;
                        installedSolution.Retract(GetImmediateJobTime(), applications);
                    }
                    else
                    {
                        installedSolution.Retract(GetImmediateJobTime());
                    }
                }
                return true;
            }

            catch (SqlException ex)
            {
                throw new Exception(ex.Message, ex);
            }
        }
    }

}
